package com.macro.mall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.google.gson.internal.LinkedHashTreeMap;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.dao.PortalMemberPriceDao;
import com.macro.mall.portal.dao.PortalProductDao;
import com.macro.mall.portal.dao.PortalSkuStockDao;
import com.macro.mall.portal.domain.CombinedPmsProduct;
import com.macro.mall.portal.domain.MemberProductCollection;
import com.macro.mall.portal.domain.PmsPortalProductDetail;
import com.macro.mall.portal.domain.PmsProductCategoryNode;
import com.macro.mall.portal.dto.PmsProductDto;
import com.macro.mall.portal.dto.PmsSkuStockMemberPrice;
import com.macro.mall.portal.dto.SmsCouponGetDto;
import com.macro.mall.portal.service.MemberCollectionService;
import com.macro.mall.portal.service.OmsPromotionService;
import com.macro.mall.portal.service.PmsPortalProductService;
import com.macro.mall.portal.service.UmsMemberService;
import com.quyum.mall.market.config.RedisKey;
import com.quyum.mall.market.dto.MarketSmsGroupBuyDTO;
import com.quyum.mall.market.entity.MarketSmsRound;
import com.quyum.mall.market.entity.MarketSmsRoundProduct;
import com.quyum.mall.market.example.MarketSmsGroupBuyOrderExample;
import com.quyum.mall.market.mapper.MarketSmsGroupBuyMapper;
import com.quyum.mall.market.mapper.MarketSmsGroupBuyOrderMapper;
import com.quyum.mall.market.mapper.MarketSmsRoundMapper;
import com.quyum.mall.market.service.activity.GroupBuyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service实现类
 * Created by macro on 2020/4/6.
 */
@Service
public class PmsPortalProductServiceImpl implements PmsPortalProductService {
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsBrandMapper brandMapper;
    @Autowired
    private PmsProductAttributeMapper productAttributeMapper;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PortalProductDao portalProductDao;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Autowired
    private PortalSkuStockDao portalSkuStockDao;
    @Autowired
    private PmsCombinedProductMapper combinedProductMapper;
    @Autowired
    private PortalMemberPriceDao memberPriceDao;
    @Autowired
    private MemberCollectionService memberCollectionService;
    @Autowired
    private SmsCouponHistoryMapper couponHistoryMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MarketSmsRoundMapper roundMapper;
    @Autowired
    private OmsPromotionService omsPromotionService;
    @Autowired
    private GroupBuyService groupBuyService;
    @Autowired
    private MarketSmsGroupBuyMapper smsGroupBuyMapper;
    @Autowired
    private MarketSmsGroupBuyOrderMapper groupBuyOrderMapper;
    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;
    @Autowired
    private PmsMemberPriceMapper priceMapper;


    @Override
    public CommonResult<CommonPage<PmsProductDto>> search(String keyword, Integer recommandStatus, Long productCategoryId, Long storeId, Integer pageNum, Integer pageSize, Integer sort) {
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        if(storeId != null){
            criteria.andStoreIdEqualTo(storeId);
        }
        criteria.andDeleteStatusEqualTo(0)
                .andVerifyStatusEqualTo(1)
                .andPublishStatusEqualTo(1);
        if (StrUtil.isNotEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
        }
        if (recommandStatus != null) {
            criteria.andRecommandStatusEqualTo(recommandStatus);
        }
        if (productCategoryId != null) {
            criteria.andProductCategoryIdEqualTo(productCategoryId);
        }
        //1->按新品；2->按销量；3->价格从低到高；4->价格从高到低
        if (sort == 1) {
            example.setOrderByClause("id desc");
        } else if (sort == 2) {
            example.setOrderByClause("sale desc");
        } else if (sort == 3) {
            example.setOrderByClause("price asc");
        } else if (sort == 4) {
            example.setOrderByClause("price desc");
        }
        //处理会员价
        PageHelper.startPage(pageNum, pageSize);
        List<PmsProduct> pmsProducts = productMapper.selectByExample(example);
        CommonPage<PmsProduct> page = CommonPage.restPage(pmsProducts);
        List<PmsProduct> list = page.getList();
        List<PmsProductDto> dto = getMemberPrice(list, storeId);
        CommonPage<PmsProductDto> result = new CommonPage<>();
        BeanUtils.copyProperties(page, result);
        result.setList(dto);
//        PageHelper.clearPage();
        return CommonResult.success(result);
    }

    @Override
    public List<PmsProductCategory> categoryTreeList(Long storeId) {

        PmsProductCategoryExample example = new PmsProductCategoryExample();
        example.createCriteria().andStoreIdEqualTo(storeId).andShowStatusEqualTo(1);
        example.setOrderByClause("sort");
        List<PmsProductCategory> allList = productCategoryMapper.selectByExample(example);
        return allList;
    }

    @Override
    public PmsPortalProductDetail detail(Long id,MarketSmsGroupBuyDTO groupBuyDTO) {
        UmsMember currentMember = memberService.getCurrentMember();
        PmsPortalProductDetail result = new PmsPortalProductDetail();
//        获取商品详情
        PmsProduct product = productMapper.selectByPrimaryKey(id);
        Boolean ret = product==null||(product.getDeleteStatus() != null && product.getDeleteStatus().equals(1)) || (product.getPublishStatus() != null && product.getPublishStatus().equals(0));
        if(ret){
            return null;
        }
//        组装组合商品
        CombinedPmsProduct combinedPmsProduct = getCombinedPmsProduct(result, product);
        if(combinedPmsProduct==null){
            return result;
        }
        result.setProduct(combinedPmsProduct);
//        获取商品SKU库存信息
        PmsSkuStockExample skuExample = new PmsSkuStockExample();
        skuExample.createCriteria().andProductIdEqualTo(product.getId());
        List<PmsSkuStock> skuStockList = skuStockMapper.selectByExample(skuExample);
        if (CollectionUtils.isEmpty(skuStockList)) {
            return result;
        }
        List<PmsSkuStockMemberPrice> stockList = new ArrayList<>();

        //获取会员价
        stockList = this.getPmsSkuStockMemberPrices(product, skuStockList,groupBuyDTO);
//        价格区间，如果是会员，取会员价区间
        this.getMaxMinPrice(currentMember, result, skuStockList, stockList);
//        获取活动信息
        Long roundId = getRoundId(id, stockList);
        result.setSkuStockList(stockList);
        result.setRoundId(roundId);
        Map<String, List<String>> attribute = new LinkedHashTreeMap<>();
        if (!CollectionUtils.isEmpty(stockList)) {
            for (PmsSkuStock stock : stockList) {
                String spData = stock.getSpData();
                this.getSpDataMap(attribute, spData);
            }
        }
        result.setAttributeMap(attribute);
        //商品是否已收藏
        MemberProductCollection memberProductCollection = this.memberCollectionService.detail(id);
        if (memberProductCollection != null) {
            result.setCollect(1);
        } else {
            result.setCollect(0);
        }
        //商品可用优惠券
        List<SmsCouponGetDto> getDto = this.getSmsCouponGetDtos(currentMember, product);
        result.setCouponList(getDto);
        return result;
    }

    /**
     * 获取活动信息
     * @param id
     *          商品id
     * @param stockList
     *          库存列表
     * @return
     */
    public Long getRoundId(Long id, List<PmsSkuStockMemberPrice> stockList) {
        Long roundId = null;
        for (PmsSkuStockMemberPrice pms: stockList) {
            Integer type = pms.getType();
            String skuStockKey = new StringBuffer(RedisKey.ROUND_SKU_STOCK_KEY).append(pms.getProductId()).append("_").append(pms.getId()).toString();
            Object o = this.redisService.get(skuStockKey);
            if(o!=null){
                MarketSmsRoundProduct roundProduct= (MarketSmsRoundProduct)o;
                type = roundProduct.getType();
                MarketSmsRound marketSmsRound = this.roundMapper.selectByPrimaryKey(roundProduct.getRoundId());
                roundId = marketSmsRound.getId();
                //活动结束时间
                pms.setActivityEndTime(marketSmsRound.getEndTime());
                //活动金额
                pms.setActivityPrice(roundProduct.getActivityPrice());
                pms.setNum(roundProduct.getNum());
                pms.setResidueNum(roundProduct.getResidueNum());
                pms.setRoundId(roundId);
                if(type==3){
                    //成团人数
                    pms.setGroupSize(roundProduct.getGroupSize());
                    //成团订单，展示两条
                    CommonPage<MarketSmsGroupBuyDTO> groupBuyByProductId = this.groupBuyService.getGroupBuyByProductId(roundProduct.getRoundId(),id, 1, 2);
                    List<MarketSmsGroupBuyDTO> list = groupBuyByProductId.getList();
                    pms.setGroupList(list);
                    //已经拼团的人数
                    Integer bodyNum = this.groupBuyService.getOrderNumByProductId(id, marketSmsRound.getId());
                    pms.setGroupBodyNum(bodyNum);
                }
            }
            pms.setType(type);
        }
        return roundId;
    }

    /**
     * 处理最高价格和最低价格
     * @param currentMember
     * @param result
     * @param skuStockList
     * @param stockList
     */
    public void getMaxMinPrice(UmsMember currentMember, PmsPortalProductDetail result, List<PmsSkuStock> skuStockList, List<PmsSkuStockMemberPrice> stockList) {
        BigDecimal maxPrice = BigDecimal.ZERO;
        BigDecimal minPrice = BigDecimal.ZERO;
        BigDecimal maxMemberPrice = BigDecimal.ZERO;
        BigDecimal minMemberPrice = BigDecimal.ZERO;
//        if (currentMember != null && currentMember.getMemberLevel() != null && !currentMember.getMemberLevel().equals(1) && currentMember.getMemberLevelEndTime().after(new Date())) {
        //是会员
        Optional<PmsSkuStockMemberPrice> max = stockList.stream().max(Comparator.comparing(PmsSkuStockMemberPrice::getMemberPrice));
        PmsSkuStockMemberPrice pmsSkuStock = null;
        pmsSkuStock = max.orElseGet(() -> stockList.get(0));
        maxMemberPrice = pmsSkuStock.getMemberPrice();
        Optional<PmsSkuStockMemberPrice> min = stockList.stream().min(Comparator.comparing(PmsSkuStockMemberPrice::getMemberPrice));
        if (min.isPresent()) {
            minMemberPrice = min.get().getMemberPrice();
        }
//        }else{
        //不是会员
        Optional<PmsSkuStockMemberPrice> max1 = stockList.stream().max(Comparator.comparing(PmsSkuStock::getPrice));
        PmsSkuStock pmsSkuStock1 = null;
        if (!max1.isPresent()) {
            pmsSkuStock1 = skuStockList.get(0);
        } else {
            pmsSkuStock1 = max1.get();
        }
        maxPrice = pmsSkuStock1.getPrice();
        Optional<PmsSkuStockMemberPrice> min1 = stockList.stream().min(Comparator.comparing(PmsSkuStock::getPrice));
        if (min1.isPresent()) {
            minPrice = min1.get().getPrice();
        }
//        }
        result.setMaxPrice(maxPrice);
        result.setMinPrice(minPrice);
        result.setMaxMemberPrice(maxMemberPrice);
        result.setMinMemberPrice(minMemberPrice);

    }

    /**
     * 获取会员价
     * @author zhouboyu
     * @Date 2020年10月29日
     * @param product
     * @param skuStockList
     * @return
     */
    public List<PmsSkuStockMemberPrice> getPmsSkuStockMemberPrices(PmsProduct product, List<PmsSkuStock> skuStockList,MarketSmsGroupBuyDTO groupBuyDTO) {
        List<PmsSkuStockMemberPrice> stockList = new ArrayList<>();
        Long groupBuySkuId =null;
        if(groupBuyDTO !=null){
            Long firstOrderId = groupBuyDTO.getFirstOrderId();
            OmsOrderItemExample omsOrderItemExample = new OmsOrderItemExample();
            omsOrderItemExample.createCriteria().andOrderIdEqualTo(firstOrderId);
            List<OmsOrderItem> omsOrderItems = this.omsOrderItemMapper.selectByExample(omsOrderItemExample);
            if(!CollectionUtils.isEmpty(skuStockList)){
                groupBuySkuId = omsOrderItems.get(0).getProductSkuId();
            }
        }
        if(groupBuySkuId!=null){
            Long finalGroupBuySkuId = groupBuySkuId;
            skuStockList = skuStockList.stream().filter(e -> e.getId().equals(finalGroupBuySkuId)).collect(Collectors.toList());
        }
        for (PmsSkuStock e: skuStockList) {
            BigDecimal memberPrice = memberPriceDao.getMemberPrice(e.getId(), e.getStoreId());
            PmsSkuStockMemberPrice pms = new PmsSkuStockMemberPrice();
            BeanUtils.copyProperties(e,pms);
            pms.setMemberPrice(memberPrice);
            Integer type  = product.getType();
            pms.setType(type);
            stockList.add(pms);
        }
        return stockList;
    }

    /**
     * 组装组合商品
     * @author zhouboyu
     * @Date 2020年10月29日
     * @param result
     * @param product
     * @return
     */
    public CombinedPmsProduct getCombinedPmsProduct(PmsPortalProductDetail result, PmsProduct product) {
        CombinedPmsProduct combinedPmsProduct = new CombinedPmsProduct();
        if (product.getType()!=null&& product.getType().equals(0)) {
            BeanUtils.copyProperties(product, combinedPmsProduct);
            combinedPmsProduct.setPmsSkuStock(new PmsSkuStock());
            combinedPmsProduct.setCombinedProductList(new ArrayList<CombinedPmsProduct>());
        } else {
            //组合商品
            PmsSkuStockExample example = new PmsSkuStockExample();
            example.createCriteria()
                    .andProductIdEqualTo(product.getId());
            //该商品的所有规格
            List<PmsSkuStock> pmsSkuStocks = this.pmsSkuStockMapper.selectByExample(example);
            //所有的规格id
            List<Long> collect = pmsSkuStocks.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                List<CombinedPmsProduct> combinedPmsProducts = this.portalSkuStockDao.queryProductsByCombineParentIds(collect);
                if(combinedPmsProducts.size()>0){
                    //如果子规格的商品下架或删除了，该组合商品不显示了
                    for (CombinedPmsProduct com: combinedPmsProducts) {
                        List<CombinedPmsProduct> combinedProductList = com.getCombinedProductList();
                        for (CombinedPmsProduct combined : combinedProductList) {
                            if (combined.getDeleteStatus().equals(1) || combined.getPublishStatus().equals(0)) {
                                result.setSubStatus(1);
                                return null;
                            }
                        }
                    }
                    combinedPmsProduct = combinedPmsProducts.get(0);
                    //处理子规格和省的钱
                    CombinedPmsProduct pmsProduct = this.savePrice(combinedPmsProduct);
                    pmsProduct.setSavePrice(pmsProduct.getOriginalPrice().subtract(pmsProduct.getPrice()));
                    //库存
                    Integer combinedStock = omsPromotionService.getCombinedStock(pmsSkuStocks.get(0).getId(), null,0);
                    combinedPmsProduct.setStock(combinedStock);
                    combinedPmsProduct.getPmsSkuStock().setStock(combinedStock);
                    combinedPmsProduct = pmsProduct;
                }
            }
        }
        return combinedPmsProduct;
    }

    /**
     * 获取优惠券列表
     * @author zhouboyu
     * @Date 2020年10月29日
     * @param currentMember
     * @param product
     * @return
     */
    public List<SmsCouponGetDto> getSmsCouponGetDtos(UmsMember currentMember, PmsProduct product) {
        List<SmsCouponGetDto> getDto = new ArrayList<>();
        if(currentMember != null){
            List<SmsCoupon> smsCoupons = portalProductDao.getAvailableCouponList(product.getId(), product.getProductCategoryId());
            if(!CollectionUtils.isEmpty(smsCoupons)){
                List<SmsCoupon> collect = smsCoupons.stream().filter(e -> e.getStoreId().equals(currentMember.getStoreId())).collect(Collectors.toList());
                for (SmsCoupon smsCoupon : collect) {
                    //查询每张优惠券限领张数
                    Integer perLimit = smsCoupon.getPerLimit();
                    SmsCouponHistoryExample example = new SmsCouponHistoryExample();
                    if(currentMember.getStoreId()!=null){
                        example.createCriteria().andCouponIdEqualTo(smsCoupon.getId()).andMemberIdEqualTo(currentMember.getId()).andStoreIdEqualTo(currentMember.getStoreId());
                    }
                    List<SmsCouponHistory> smsCouponHistories = couponHistoryMapper.selectByExample(example);
                    SmsCouponGetDto dto = new SmsCouponGetDto();
                    BeanUtils.copyProperties(smsCoupon, dto);
                    if(smsCouponHistories.size() < perLimit){
                        dto.setGetType(0);
                    }else{
                        dto.setGetType(1);
                    }
                    getDto.add(dto);
                }
            }
        }
        return getDto;
    }

    /**
     * 获取规格信息，前端铺页面使用
     * @param attribute
     * @param spData
     */
    public void getSpDataMap(Map<String, List<String>> attribute, String spData) {
        if (StringUtils.isNotBlank(spData)) {
            List<Map<String, String>> listMap = JSON.parseObject(spData, List.class);
            List<String> list;
            for (Map<String, String> map : listMap) {
                String key = map.get("key");
                String value = map.get("value");
                if (attribute.get(key) != null) {
                    list = attribute.get(key);
                    if (!list.contains(value)) {
                        list.add(value);
                    }
                } else {
                    list = new ArrayList<>();
                    list.add(value);
                }
                attribute.put(key, list);
            }
        }
    }

    @Override
    public CommonPage<CombinedPmsProduct> getCombinedPmsProduct(Long memberId, Integer pageNum, Integer pageSize) {
        UmsMember currentMember = memberService.getById(memberId);
        Long storeId = null;
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample example = new PmsProductExample();
        PmsProductExample.Criteria criteria = example.createCriteria();
        if (currentMember != null ) {
            storeId = currentMember.getStoreId();
            criteria.andStoreIdEqualTo(storeId);
        }
        criteria.andTypeEqualTo(1)
                .andDeleteStatusEqualTo(0)
                .andVerifyStatusEqualTo(1)
                .andPublishStatusEqualTo(1);
        List<PmsProduct> pmsProducts = this.productMapper.selectByExample(example);
        //处理分页
        CommonPage<PmsProduct> pmsProductCommonPage = CommonPage.restPage(pmsProducts);
        List<PmsProduct> list = pmsProductCommonPage.getList();
        List<Long> ids = list.stream().map(PmsProduct::getId).collect(Collectors.toList());
        List<CombinedPmsProduct> combinedPmsProductList = new ArrayList<>();
        CommonPage<CombinedPmsProduct> resultPage = new CommonPage<>();
        if(!CollectionUtils.isEmpty(ids)){
            PmsSkuStockExample stockExample = new PmsSkuStockExample();
            PmsSkuStockExample.Criteria criteria1 = stockExample.createCriteria();
            if (storeId != null) {
                criteria1.andStoreIdEqualTo(storeId);
            }
            criteria1.andProductIdIn(ids);
            List<PmsSkuStock> pmsSkuStocks = this.pmsSkuStockMapper.selectByExample(stockExample);
            List<Long> collect = pmsSkuStocks.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            combinedPmsProductList = this.portalSkuStockDao.queryProductsByCombineParentIds(collect);
            List<CombinedPmsProduct> result = new ArrayList<>();
            if (!CollectionUtils.isEmpty(combinedPmsProductList)) {
                for (CombinedPmsProduct combinedPmsProduct : combinedPmsProductList) {
                    BigDecimal price = memberPriceDao.getMemberPrice(combinedPmsProduct.getPmsSkuStock().getId(), currentMember.getStoreId());
                    if (price != null) {
                        combinedPmsProduct.setMemberPrice(price);
                    }
                    combinedPmsProduct = savePrice(combinedPmsProduct);
                    //查找组合商品库存
                    PmsSkuStockExample example1 = new PmsSkuStockExample();
                    example1.createCriteria().andProductIdEqualTo(combinedPmsProduct.getId());
                    List<PmsSkuStock> pmsSkuStocks1 = pmsSkuStockMapper.selectByExample(example1);
                    Integer combinedStock = omsPromotionService.getCombinedStock(pmsSkuStocks1.get(0).getId(), null,0);
                    combinedPmsProduct.setStock(combinedStock);
                    combinedPmsProduct.getPmsSkuStock().setStock(combinedStock);
                    result.add(combinedPmsProduct);

                }
            }
        }
        BeanUtils.copyProperties(pmsProductCommonPage, resultPage);
        resultPage.setList(combinedPmsProductList);
        return resultPage;

    }

    @Override
    public List<CombinedPmsProduct> getCombinedPmsProductRecommend(Long memberId) {
        UmsMember currentMember = memberService.getById(memberId);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria()
                .andStoreIdEqualTo(currentMember.getStoreId())
                .andTypeEqualTo(1);//.andRecommandStatusEqualTo(1)
        List<PmsProduct> pmsProducts = this.productMapper.selectByExample(example);
        List<Long> ids = pmsProducts.stream().map(PmsProduct::getId).collect(Collectors.toList());
        PmsSkuStockExample stockExample = new PmsSkuStockExample();
        stockExample.createCriteria().andStoreIdEqualTo(currentMember.getStoreId())
                .andProductIdIn(ids);
        List<PmsSkuStock> pmsSkuStocks = this.pmsSkuStockMapper.selectByExample(stockExample);
        List<Long> collect = pmsSkuStocks.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        List<CombinedPmsProduct> combinedPmsProductList = this.portalSkuStockDao.queryProductsByCombineParentIds(collect);
//        CombinedPmsProduct combinedPmsProduct = combinedPmsProductList.get(0);
        List<CombinedPmsProduct> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(combinedPmsProductList)) {
            for (CombinedPmsProduct combinedPmsProduct : combinedPmsProductList) {
                BigDecimal price = memberPriceDao.getMemberPrice(combinedPmsProduct.getPmsSkuStock().getId(), currentMember.getStoreId());
                if (price != null) {
                    combinedPmsProduct.setMemberPrice(price);
                }
                combinedPmsProduct = savePrice(combinedPmsProduct);
                result.add(combinedPmsProduct);
            }
        }

        return result;
    }


    /**
     * 初始对象转化为节点对象
     */
    private PmsProductCategoryNode covert(PmsProductCategory item, List<PmsProductCategory> allList) {
        PmsProductCategoryNode node = new PmsProductCategoryNode();
        BeanUtils.copyProperties(item, node);
        List<PmsProductCategoryNode> children = allList.stream()
                .filter(subItem -> subItem.getParentId().equals(item.getId()))
                .map(subItem -> covert(subItem, allList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }

    private Map<String, List<String>> getSpData(Map<String, List<String>> attribute, String spData) {
        getSpDataMap(attribute, spData);
        return attribute;
    }


    /**
     * 处理套餐价和子商品
     *
     * @param combinedPmsProduct
     * @param combinedPmsProduct
     * @return
     */
    @Override
    public CombinedPmsProduct savePrice(CombinedPmsProduct combinedPmsProduct) {
        BigDecimal pro = combinedPmsProduct.getPrice();
        BigDecimal savePrice = BigDecimal.ZERO;
        BigDecimal sum = BigDecimal.ZERO;//子商品的和
        BigDecimal price = BigDecimal.ZERO;
        List<CombinedPmsProduct> combinedProductList = combinedPmsProduct.getCombinedProductList();
        List<CombinedPmsProduct> combinedPmsProductList = new ArrayList<>();
        for (CombinedPmsProduct combined : combinedProductList) {
            price = combined.getPmsSkuStock().getPrice();//每个子商品的规格
            sum = sum.add(price);//加到子商品的和中
            String spData = combined.getPmsSkuStock().getSpData();
            Map<String, List<String>> attr = new HashMap<>();
            Map<String, List<String>> sp = getSpData(attr, spData);
            combined.setAttributeMap(sp);
            combinedPmsProductList.add(combined);
        }
        savePrice = sum.subtract(pro);
        savePrice =savePrice.setScale(2, RoundingMode.HALF_UP);
        combinedPmsProduct.setNotPackagePrice(sum);
        combinedPmsProduct.setSavePrice(savePrice);
        combinedPmsProduct.setCombinedProductList(combinedPmsProductList);
        return combinedPmsProduct;
    }

    @Override
    public List<PmsProductDto> getMemberPrice(List<PmsProduct> pmsProducts, Long storeId){
        List<PmsProductDto> result = new ArrayList<>();
        for (PmsProduct product : pmsProducts) {
            PmsProductDto dto = new PmsProductDto();
            BeanUtils.copyProperties(product, dto);
            PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
            skuStockExample.createCriteria().andProductIdEqualTo(product.getId());
            List<PmsSkuStock> pmsSkuStocks = skuStockMapper.selectByExample(skuStockExample);
            if (!CollectionUtils.isEmpty(pmsSkuStocks)) {
                Optional<PmsSkuStock> min = pmsSkuStocks.stream().min(Comparator.comparing(PmsSkuStock::getPrice));
                PmsSkuStock pmsSkuStock = null;
                if(min.isPresent()){
                    pmsSkuStock = min.get();
                }else {
                    pmsSkuStock = pmsSkuStocks.get(0);
                }
                PmsMemberPriceExample priceExample = new PmsMemberPriceExample();
                priceExample.createCriteria().andProductStockIdEqualTo(pmsSkuStock.getId());
                List<PmsMemberPrice> pmsMemberPrices = priceMapper.selectByExample(priceExample);
                dto.setPmsSkuStock(pmsSkuStock);
                dto.setPrice(pmsSkuStock.getPrice());
                dto.setMemberPrice(pmsMemberPrices.get(0).getMemberPrice());
            }
            result.add(dto);
        }
        return result;
    }
}
